package com.atguigu.gmall.cart.controller;



import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.cart.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;


    @GetMapping("user/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCartByUserId(@PathVariable Long userId){
        List<Cart> list = cartService.queryCartByUserId(userId);
        return ResponseVo.ok(list);
    }
    @GetMapping
    public String addCart(Cart cart){
        cartService.addCart(cart);
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }
    @GetMapping("addCart.html")
    public String queryCart(Cart cart, Model model){
        //覆盖购物车对象前先获取本次新增的数量
        BigDecimal cartCount = cart.getCount();
        //用数据库查询到的对象覆盖cart对象
        cart = cartService.queryCartBySkuId(cart.getSkuId());
        cart.setCount(cartCount);
        model.addAttribute("cart",cart);
        return "addCart";
    }

    @GetMapping("cart.html")
    public String queryCarts(Model model){
        List<Cart> cart = cartService.queryCarts();
        model.addAttribute("carts",cart);
        return "cart";
    }

    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteSkuId(@RequestParam Long skuId){
        cartService.deleteBySkuId(skuId);
        return ResponseVo.ok();
    }
}
